#include "session.h"

Session::Session()
{
	Init();
}

Session::~Session()
{
}

void Session::Init()
{
	m_RecvBuf.Init();
	m_SendBuf.Init();
	m_IsFree = true;
}

int Session::GetFd()
{
	return m_fd;
}

void Session::SetFd(int fd)
{
	m_fd = fd;
}

Buffer * Session::GetRecvBuf()
{
	return &m_RecvBuf;
}

Session * SessionMgr::CreateSession(int fd)
{
	for(int i = 0; i < m_MaxFreeSession; ++i)
	{
		Session * pSess = m_FreeSessions + i;
		if(pSess->m_IsFree)
		{
			pSess->Init();
			pSess->m_IsFree = false;
			pSess->SetFd(fd);
			m_Sessions.insert(pair<int, Session *>(fd, pSess));
			return pSess;
		}
	}
	return NULL;
}

Session * SessionMgr::GetSession(int fd)
{
	map<int, Session *>::iterator p = m_Sessions.find(fd);
	if(p != m_Sessions.end())
	{
		return p->second;
	}
	return NULL;
}

void SessionMgr::FreeSession(int fd)
{
	Session* pSess = GetSession(fd);
	if(pSess)
	{
		pSess->m_IsFree = true;
		m_Sessions.erase(fd);
	}
}

